#include "SelectorImpl.h"
#include <assert.h>

DescendantSelectorImpl::DescendantSelectorImpl()
	:ancestorSelector(NULL), simpleSelector(NULL)
{

}


DescendantSelectorImpl::DescendantSelectorImpl(const Selector& parent,
									 const SimpleSelector& child)
{
	ancestorSelector = parent.Copy();
	simpleSelector = dynamic_cast<SimpleSelector*>(child.Copy());
}

DescendantSelectorImpl::DescendantSelectorImpl(const DescendantSelectorImpl& aChildSelector)
{
	if(aChildSelector.ancestorSelector)
		ancestorSelector = aChildSelector.ancestorSelector->Copy();
	if(aChildSelector.simpleSelector)
		simpleSelector = dynamic_cast<SimpleSelector*>(
								aChildSelector.simpleSelector->Copy());
}

DescendantSelectorImpl::~DescendantSelectorImpl()
{
	if(ancestorSelector)
		delete ancestorSelector;
	if(simpleSelector)
		delete simpleSelector;
}

DescendantSelectorImpl& DescendantSelectorImpl::operator=(const DescendantSelectorImpl&
																		aChildSelector)
{
	if(this == &aChildSelector)
		return *this;

	if(aChildSelector.ancestorSelector)
		setAncestorSelector(*aChildSelector.ancestorSelector);
	if(aChildSelector.simpleSelector)
		setSimpleSelector(*aChildSelector.simpleSelector);
	return *this;
}

Selector* DescendantSelectorImpl::Copy()const
{
	DescendantSelectorImpl* result = new DescendantSelectorImpl();
	if(ancestorSelector)
		result->setAncestorSelector(*ancestorSelector);
	if(simpleSelector)
		result->setSimpleSelector(*simpleSelector);
	return result;
}

Selector::SelectorType DescendantSelectorImpl::getSelectorType()const
{
	return Selector::SAC_DESCENDANT_SELECTOR;
}

const string* DescendantSelectorImpl::toString()const
{
	assert(ancestorSelector && simpleSelector);

	string* result = NULL;
	try
	{
		result = new string(*(ancestorSelector->toString()));
		result->append(" ");
		result->append(*(simpleSelector->toString()));
	}catch(std::exception& e)
	{
		if(result)
			delete result;
		return NULL;
	}
	return result;
}

const Selector& DescendantSelectorImpl::getAncestorSelector()const
{
	assert(ancestorSelector);
	return *ancestorSelector;
}

const SimpleSelector& DescendantSelectorImpl::getSimpleSelector()const
{
	assert(simpleSelector);
	return *simpleSelector;
}
